package org.alis.rpc.core;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.timeout.IdleStateHandler;
import org.alis.rpc.common.bean.RpcRequest;
import org.alis.rpc.common.bean.RpcResponse;
import org.alis.rpc.common.codec.RpcDecoder;
import org.alis.rpc.common.codec.RpcEncoder;
import org.alis.rpc.common.contant.RpcConstants;
import org.alis.rpc.common.serializer.Serializer;
import org.alis.rpc.common.serializer.kryo.KryoSerializer;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * RpcServerInitializer desc: 服务初始化
 *
 * @author luochuan
 * @date 2020/10/9 15:07
 */
public class RpcServerInitializer extends ChannelInitializer<SocketChannel> {
    private Map<String, Object> handlerMap;

    public RpcServerInitializer(Map<String, Object> handlerMap) {
        this.handlerMap = handlerMap;
    }

    @Override
    public void initChannel(SocketChannel channel) throws Exception {
        Serializer serializer = KryoSerializer.class.getDeclaredConstructor().newInstance();
        ChannelPipeline cp = channel.pipeline();
        cp.addLast(new IdleStateHandler(0, 0, RpcConstants.BEAT_TIMEOUT, TimeUnit.SECONDS));
        cp.addLast(new LengthFieldBasedFrameDecoder(65536, 0, 4, 0, 0));
        cp.addLast(new RpcDecoder(RpcRequest.class, serializer));
        cp.addLast(new RpcEncoder(RpcResponse.class, serializer));
        cp.addLast(new RpcServerHandler<>(handlerMap));
    }
}
